#include "tgaimage.h"

const TGAColor white = TGAColor(255, 255, 255, 255);
const TGAColor red   = TGAColor(255, 0,   0,   255);

void line(int x0, int y0, int x1, int y1, TGAImage& image, TGAColor color)
{
    //第一个版本
    //问题：t每次增加的量是多少？很难设定
    //for (float t = 0; t < 1.; t += 0.01)
    //{
    //    int x = x0 + (x1 - x0)*t;
    //    int y = y0 + (y1 - y0)*t;
    //    image.set(x, y, color);
    //}

    //第二个版本
    //解决了第一个版本中的递增常量选取问题
    //新问题：x1-x0可能等于0; (a,b)能绘制，但(b,a)不会被绘制；斜率k>1时有缝隙
    //for (int x=x0; x<=x1; x++)
    //{
    //    float t = (x - x0) / (float)(x1 - x0);
    //    int y = y0 + t * (y1 - y0);
    //    image.set(x, y, color);
    //}
    bool steep = false;
    // if the line is steep, we transpose the image
    if (std::abs(x0 - x1) < std::abs(y0 - y1)) {
        std::swap(x0, y0);
        std::swap(x1, y1);
        steep = true;
    }
    if (x0 > x1) { // make it left-to-right
        std::swap(x0, x1);
        std::swap(y0, y1);
    }
    for (int x=x0; x<=x1; x++)
    {
        float t = (x - x0) / (float)(x1 - x0);
        int y = y0 + t * (y1 - y0);
        if (steep) { // if transposed, de-transpose
            image.set(y, x, color);
        }
        else {
            image.set(x, y, color);
        }
    }
}

int main(int argc, char** argv) {
    TGAImage image(100, 100, TGAImage::RGB);
    image.set(52, 41, red);

    line(13, 20, 80, 40, image, white);
    line(20, 13, 40, 80, image, red);
    line(80, 40, 13, 20, image, red);

    image.flip_vertically(); // i want to have the origin at the left bottom corner of the image
    image.write_tga_file("output.tga");
    return 0;
}

